#!/usr/bin/env bash
set -x
SELFDIR=$(cd $(dirname -- "${BASH_SOURCE[0]}");pwd)

# $1 initenv
# $2 devrepo_dir
function main() {
    if [[ $# -lt 1 ]]; then
        echo    "Missing parameters, try -h for help"
        return  1
    fi

    #local devrepo_conf=$(basename "$2")
    local devrepo_dir="$2"
    if [[ $# -lt 3 ]]; then
        devrepo_dir="${DEVREPO}"
        if [[ "${devrepo_dir}" == "" ]]; then
            echo    "No target initialize directory given, try -h for help"
            return  1
        fi
    fi

    if [[ ! -d "${devrepo_dir}" ]]; then
        mkdir -p "${devrepo_dir}"
        if [[ ! -d "${devrepo_dir}" ]]; then
            echo    "Can not create directory for \${DEVREPO}: '${devrepo_dir}'"
            return  1
        fi
    fi

#    if [[ ! -f "${devrepo_dir}/${devrepo_conf}" ]]; then
#        touch "${devrepo_dir}/${devrepo_conf}"
#        if [[ ! -f "${devrepo_dir}/${devrepo_conf}" ]]; then
#            echo    "Can not create configuration file for \${DEVREPO}: '${devrepo_dir}/${devrepo_conf}'"
#            return  1
#        fi
#    fi

    cp -rf  "${SELFDIR}/template"/*  "${devrepo_dir}/"      &&  \
    cp -rf  "${PKGREPO}/pkgr"        "${devrepo_dir}/"      &&  \
    "${PKGREPO}/.pkgr/install.sh"    "${devrepo_dir}/.pkgr" &&  \
    echo    "Initialize DEVREPO success: '${devrepo_dir}'"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    "Initialize DEVREPO failed(${RESULT}): '${devrepo_dir}'"
        return  1
    fi

    return 0
}

main "$@"
exit "$?"
